const express = require('express')
const Result = require('../../models/Result')
const { decoded } = require('../../utils/index')
const { PRIVATE_KEY, JWT_EXPIRED } = require('../../utils/constant')
const {
  getDeptList,
  editDept,
  createDept,
  deleteDept
} = require('../../services/dept')
const jwt = require('jsonwebtoken')
const jwtAuth = require('../jwt')
// 注册路由
const router = express.Router()
router.use(jwtAuth)

//获取部门树形结构接口
const getDeptTree = (deptList,id = 0) => {
  const result = []
  deptList.forEach(item => {
    if (item.parentId === id) {
      result.push({
        ...item,
        children: getDeptTree(deptList,item.id)
      })
    }
  })
  return result
}

//获取部门列表接口
router.get('/list', function(req, res, next) {
  getDeptList(req.query).then(data => {
    new Result(getDeptTree(data), '部门信息查询成功').success(res)
  }).catch(err => {
    new Result('部门信息查询失败').fail(res)
  })
})

//编辑部门接口
router.post('/edit', function(req, res, next) {
  editDept(req.body).then(data => {
    new Result('操作成功').success(res)
  }).catch(err => {
    new Result('操作失败').fail(res)
  })
})

//创建部门接口
router.post('/create', function(req, res, next) {
  createDept(req.body,decoded(req).cardId).then(data => {
    new Result('操作成功').success(res)
  }).catch(err => {
    new Result('操作失败').fail(res)
  })
})

//删除部门接口
router.post('/delete', function(req, res, next) {
  deleteDept(req.body).then(data => {
    new Result('操作成功').success(res)
  }).catch(err => {
    new Result('操作失败').fail(res)
  })
})


module.exports = router